package com.foreverwin.jzymes.production.tool.controller;

import com.foreverwin.jzymes.common.util.CommonMethods;
import com.foreverwin.jzymes.framework.annotation.ParamBind;
import com.foreverwin.jzymes.framework.base.AjaxResult;
import com.foreverwin.jzymes.framework.exception.BusinessException;
import com.foreverwin.jzymes.production.tool.domain.ToolBill;
import com.foreverwin.jzymes.production.tool.domain.ToolBillItem;
import com.foreverwin.jzymes.production.tool.service.IToolBillAdviceService;
import com.foreverwin.jzymes.production.tool.service.IToolBillItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/production/tool")
public class ToolBillController {
    @Autowired
    IToolBillAdviceService toolBillAdviceService;
    @Autowired
    IToolBillItemService toolBillItemService;

    /**保存刀具清单*/
    @RequestMapping("/submit")
    @ParamBind
    public AjaxResult submitToolBill( ToolBill toolBill, ArrayList<ToolBillItem> toolBillItems ) {
        try{
            toolBill.setSite( CommonMethods.getSite() );
            toolBillAdviceService.saveToolBill( toolBill, toolBillItems );
            return AjaxResult.returnSuccess();
        }catch ( BusinessException e ){
            return AjaxResult.returnError( e.getMessage() );
        }
    }

    /**检索刀具清单信息*/
    @RequestMapping("/findToolBill")
    public AjaxResult findToolBill( @RequestParam String machineType, @RequestParam String cncType, @RequestParam String toolBillRevision ) {
        try{
            String site = CommonMethods.getSite();

            ToolBill toolBill = toolBillAdviceService.findToolBill( site, machineType, cncType, toolBillRevision );

            if( toolBill != null ){
                ToolBillItem queryParam = new ToolBillItem();
                queryParam.setToolBillBo( toolBill.getHandle() );
                List<ToolBillItem> toolBillItems = toolBillItemService.selectToolBillItemList( queryParam );

                Boolean isHistoryRevision = toolBillAdviceService.isHistoryRevision( toolBill );
                Map<String,Object> returnMap = new HashMap<>();
                returnMap.put( "isHistoryRevision", isHistoryRevision );
                returnMap.put( "toolBill", toolBill );
                returnMap.put( "toolList", toolBillItems );

                return AjaxResult.returnSuccess().put("value", returnMap );
            }

            return AjaxResult.returnSuccess();
        }catch ( BusinessException e ){
            return AjaxResult.returnError(e.getMessage());
        }
    }
}
